# -*- coding:utf-8 -*-


import time
import json
import config
import pymongo
from scrapy import Spider
from scrapy.http import Request


class OkexExchange(Spider):
    name = 'okex'

    def __init__(self, name=None, **kwargs):
        super(OkexExchange, self).__init__(name, **kwargs)

        # 把URL存到reids中，这里使用的是reids的列表操作
        self.pairs = ['btc_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']

        # 连接mongodb
        # client = pymongo.MongoClient('localhost', 27017)
        client = pymongo.MongoClient('47.254.26.182', 27017)
        self.db = client.bt_news

    def start_requests(self):
        for pair in self.pairs:
            # https://www.okex.com/api/v1/future_ticker.do?symbol=btc_usd&contract_type=this_week
            url = 'https://www.okex.com/api/v1/future_ticker.do?symbol=%s&contract_type=this_week' % pair

            yield Request(
                url=url,
                dont_filter=True,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
                },
                meta={

                },
                callback=self.exchange_info
            )

    def exchange_info(self, response):
        # 获取json中的数据，对应交易所信息
        body = json.loads(response.body)
        ticker = body.get('ticker')

        okcoin_url = response.url
        # 交易对
        exchange_pair = okcoin_url.split('=')[1]
        pair = exchange_pair.split('_')
        pair_name = pair[0]
        variual_pair = pair[1]

        # 交易所名称
        exchange_name = 'okex'

        # 买家
        buy = ticker.get('buy')

        # 卖价
        sell = ticker.get('sell')

        # 最高价
        high = ticker.get('high')

        # 最低价
        low = ticker.get('low')

        # 成交量
        vol = ticker.get('vol')

        # 时间
        okcoin_time = body.get('date')

        # 最新成交价
        last = ticker.get('last')

        # 入库mongo
        data = {
            'exchange_name': exchange_name,
            'variual_coin_name': pair_name,
            'variual_pair': variual_pair,
            # 'market_value': market_value,
            'buy': buy,
            'sell': sell,
            'high': high,
            'low': low,
            'last': last,
            'vol': vol,
            'time': okcoin_time,
            # 'roportion': roportion,
            # 'hasklin': hasklin,
            # 'change1d': change1d,
            'updatetime': time.localtime()
        }

        # 入库mongo
        if response.status == 200:
            self.db.bt_coin.update_one({'exchange_name': exchange_name, 'variual_coin_name': pair_name, 'variual_pair': variual_pair},
                                       {'$set': data}, upsert=True)

        # 循环更新数据
        url = response.url
        yield Request(
            url=url,
            dont_filter=True,
            headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
            },
            meta={

            },
            callback=self.exchange_info
        )


'''
每三秒更新mongo中的数据
'''